package org.neptune.service.service.impl;

import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.neptune.api.entity.AesKeyBean;
import org.neptune.api.entity.SeckillUser;
import org.neptune.api.request.LoginRequest;
import org.neptune.common.constant.NeptuneConstant;
import org.neptune.common.response.ResponseBean;
import org.neptune.common.util.AESUtils;
import org.neptune.common.util.SecurityKeyUtil;
import org.neptune.service.config.NeptuneConfig;
import org.neptune.service.redis.RedisRepository;
import org.neptune.service.redis.RedissonUtil;
import org.neptune.service.service.IndexService;
import org.neptune.service.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

/**
 * @author lwl
 * @date 2019/9/27 15:16
 */
@Service
public class IndexServiceImpl implements IndexService {

	@Autowired
	private RedisRepository redisRepository;

	@Autowired
	private UserService userService;

	@Autowired
	private NeptuneConfig neptuneConfig;

	@Override
	public ResponseBean<Object> loginVerify(LoginRequest loginRequest) throws Exception {
		// 获取秘钥
		String cacheKey = RedissonUtil.getRedisKey(NeptuneConstant.REDIS_RSAKEY_SESSION,
				loginRequest.getToken());
		AesKeyBean aesKeyBean = redisRepository.get(cacheKey, AesKeyBean.class);

		if (null == aesKeyBean){
			return ResponseBean.fail(null, "操作超时");
		}

		// 密码还原
		String password = SecurityKeyUtil.decryptAES(loginRequest.getPassword(),
				aesKeyBean.getAseKey());

		Subject currentUser = SecurityUtils.getSubject();

		String encryptPwd = AESUtils.encrypt(password, NeptuneConstant.PASSWORD_ENCRYPT_KEY);

		// 登录
		currentUser.login(new UsernamePasswordToken(loginRequest.getUsername(), encryptPwd));
		// 从session取出用户信息
		SeckillUser user = (SeckillUser) currentUser.getPrincipal();
		if (user == null){
			throw new AuthenticationException();
		}

		Map<String, Object> result = Maps.newHashMap();
		result.put("redirectUrl", neptuneConfig.loginDefaultPage);
		return ResponseBean.success(result, "登录成功");
	}
}
